package com.loong.seller.handler;

import com.loong.seller.business.ShopDeliveryBusiness;
import com.loong.seller.common.backend.param.ShopParam;
import com.loong.seller.model.ShopDelivery;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Description: 店铺配送方式服务
 * @Author: hzp
 * @Date: 2020-11-9 9:42
 */
@Component
public class ShopDeliveryHandler {
    @Resource
    private ShopDeliveryBusiness shopDeliveryBusiness;

    public void save(ShopParam param){
        List<Long> deliveryWaysIds = param.getDeliveryWaysIds();

        //添加店铺配送方式
        Long shopId = param.getId();
        List<ShopDelivery> modelList = deliveryWaysIds.stream().map(
                deliveryWaysId ->
                        ShopDelivery.builder().shopId(shopId).deliveryId(deliveryWaysId).selected(false).build()
        ).collect(Collectors.toList());
        shopDeliveryBusiness.save(modelList);
    }

    public void deleteByShopId(Long shopId){
        shopDeliveryBusiness.deleteByCondition(shopId);
    }

    public List<ShopDelivery> findListByShopId(Long shopId){
       return shopDeliveryBusiness.findAllBy("shopId",shopId);
    }

    public void update(ShopDelivery shopDelivery){
        shopDeliveryBusiness.updateByPrimaryKeySelective(shopDelivery);
    }

    public void setSelected(ShopDelivery shopDelivery){
        if(shopDelivery.getSelected()){
            Long shopId = shopDelivery.getShopId();
            List<ShopDelivery> byCondition = this.findByCondition(shopId,true);
            if(!CollectionUtils.isEmpty(byCondition)){
                Long id = byCondition.get(0).getId();
                ShopDelivery shopDeliverySelected = new ShopDelivery();
                shopDeliverySelected.setSelected(false);
                shopDeliverySelected.setId(id);
                shopDeliveryBusiness.updateByPrimaryKeySelective(shopDeliverySelected);
            }
            shopDeliveryBusiness.updateByPrimaryKeySelective(shopDelivery);
        }
    }

    public List<ShopDelivery> findByCondition(Long shopId ,Boolean selected){
        Condition condition = new Condition(ShopDelivery.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("shopId", shopId);
        criteria.andEqualTo("selected", selected);
        List<ShopDelivery> byCondition = shopDeliveryBusiness.findByCondition(condition);
        return byCondition;
    }



}
